package main

import (
	"12.2-gokit/Services/UserEndpoint"
	"12.2-gokit/Services/UserService"
	"12.2-gokit/Services/UserTransport"
	"12.2-gokit/util"
	"fmt"
	httptransport "github.com/go-kit/kit/transport/http"
	"github.com/gorilla/mux"
	//consulapi "github.com/hashicorp/consul/api"
	"flag"
	_ "github.com/jinzhu/gorm"
	"log"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"syscall"
)
import _ "github.com/go-sql-driver/mysql"


func main()  {
	name := flag.String("name", "", "Service Name")
	port := flag.Int("port", 0, "Service port")
	flag.Parse()
	util.SetServiceNameAndPort(*name,*port)


	user := UserService.UserService{}
	endp := UserEndpoint.GenUserEndpoint(user)

	serverHandler := httptransport.NewServer(endp, UserTransport.DecodeUserRequest, UserTransport.EncodeUserResponse)

	r := mux.NewRouter()
	r.Methods("GET").Path("/user/{uid:\\d+}").Handler(serverHandler)
	r.Methods("GET").Path("/health").HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		//vars := mux.Vars(request)
		writer.Header().Set("Content-type", "application/json")
		writer.Write([]byte(`{"status":"ok"}`))
	})
	util.RegService()
	http.ListenAndServe(":" + strconv.Itoa(*port), r)
	errChan := make(chan error)
	go func() {
		util.RegService()
		err := http.ListenAndServe(":"+strconv.Itoa(*port),r)
		if err != nil {
			log.Fatal("http.ListenAndServe err", err)
			errChan <- err
		}
	}()
	go func() {
		sig_c := make(chan os.Signal)
		signal.Notify(sig_c,syscall.SIGINT,syscall.SIGTERM)
		errChan<-fmt.Errorf("%s",<-sig_c)
	}()
	getErr := <- errChan
	util.UnRegService()
	log.Fatal(getErr)
}

